# Burning process is just randomly change one point and then
# calculate the P(n,r), and compare it with the observed on
# accpet the changed point if difference between P(n,r)s becomes
# smaller after the change.
# 
# Author: Guochun Shen
# Data:   2011-12-19
# Project:spatial statistic
# Email:  shenguochun@gmail.com
###############################################################################


burning=function(npoints,window,pairwise_dist_obs,pnr_surface_obs,covr,controls){
	#TODO need a point generate c code
	if(is.null(covr)){
		random_points=rpoint(npoints,win=window)
	}else{
		random_points=rpoint(npoints,covr,win=window)
	}
	#TODO need a c code to calculate half pairwise distance matrix
	pairwise_dist_ran=pairdist(random_points)
	
	#TODO need a c dode to convert the distance matrix into P(n,r) matrix
	pnr_surface_ran=pnr_surface(pairwise_dist_ran,controls)
			
	#TODO need a c control framework and comparision
	error=energe(pnr_surface_obs,pnr_surface_ran)
	
	ntried=1
	while(error>controls$tolerance & ntried<controls$Ngiveup){
		#TODO change one points and update the relavented distance
		pairwise_dist_ran=update_dist(random_points,pairwise_dist_ran,step=1)
		pnr_surface_ran=pnr_surface(pairwise_dist_ran,controls)
		#TOTO calculate the difference
		error=energe(pnr_surface_obs,pnr_surface_ran)
		ntried=ntried+1
	}
	random_points=attr(pairwise_dist_ran,"points")
	attr(random_points,"error")=error
	attr(random_points,"ntried")=ntried
	return(random_points)
}
